package cj.hrm.controller;


import cj.hrm.dto.EmployeeDto;
import cj.hrm.dto.excel.EmployeeToExcel;
import cj.hrm.listener.EmployeeListener;
import cj.hrm.service.EmployeeExcelService;
import cj.hrm.service.HrmService;
import cj.hrm.util.common.TestFileUtil;
import cj.hrm.util.common.exception.BizException;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/test")
public class TestController {

    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private HrmService hrmService;
    @Autowired
    private EmployeeExcelService employeeExcelService;

    @RequestMapping("testExcel")
    @ResponseBody
    public void writeWithoutHead() throws IOException {
//        String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
//        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
//        // 如果这里想使用03 则 传入excelType参数即可
//        EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());

        // 写法2
        // 导出文件的地址
        String fileName = TestFileUtil.getPath() + "员工列表_" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写
        ExcelWriter excelWriter = null;
        try {
            excelWriter = EasyExcel.write(fileName, EmployeeDto.class).build();
            //sheet名
            WriteSheet writeSheet = EasyExcel.writerSheet("员工列表").build();
            excelWriter.write(data(), writeSheet);
        } finally {
            // 千万别忘记finish 会帮忙关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    /**
     * 文件下载并且失败的时候返回json（默认失败了会返回一个有部分数据的Excel）
     *
     * @since 2.1.1
     */
    @RequestMapping("webDownLoadExcel")
    public void webDownLoadExcel(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("员工列表"+System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), EmployeeDto.class).autoCloseStream(Boolean.FALSE).sheet("员工列表")
                    .doWrite(data());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * 导入
     * @param file
     * @return
     */
    @RequestMapping("/import-employee-excel")
    public ResponseEntity<?> importExcel(@RequestParam(value = "file", required = false) MultipartFile file){

        try {
            EasyExcel.read(file.getInputStream(), EmployeeToExcel.class, new EmployeeListener(employeeExcelService)).sheet().doRead();
        } catch (Exception e) {
            log.info("Employee_excel上传失败");
            throw new BizException("上传失败啦");
        }

        return ResponseEntity.ok().build();
    }

    //获取需要写入的内容
    private List<EmployeeDto> data() {
        List<EmployeeDto> list = hrmService.findEmployeeDtoList();
        return list;
    }
}



